package com.zrrd.network.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

/**
 * @author WanJl
 * @version 1.0
 * @title ReceiveDemo01
 * @description 单播接收
 * @create 2023/10/21 20:02
 */
public class ReceiveDemo01 {
    public static void receive(int port) throws IOException {
        //1、创建接收端的Socket对象(DatagramSocket)
        DatagramSocket ds = new DatagramSocket(port);
        //2、创建一个数据包，用于接收数据
        byte[] bytes = new byte[1024];
        DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length);

        //3、调用DatagramSocket对象的方法接收数据
        //在接收到数据之前，当前线程会处在阻塞状态，等待数据的接收。
        ds.receive(datagramPacket);

        //4、解析数据包，并把数据在控制台显示
        String s = new String(datagramPacket.getData(), 0, datagramPacket.getLength());
        System.out.println("接收到数据："+s);
        //5、关闭接收端
        ds.close();
    }
    public static void main(String[] args) throws IOException {
        while (true) {
            receive(10086);
        }
    }
}
